<?php

namespace Library;

abstract class Action extends \Library\View {

	private $_params = array();
	private $_url;
	
	public function __construct( $params = array() ) {
		$this->_params = $params;
	}

	public function execute() {
	}
	
	public function getUrl() {
		if( $this->_url === null ) {
			$url = str_replace( '\\', '_', get_class($this) );
			$pos = strpos( $url, '_' );
			$url = substr( $url, $pos + 1 );
			if( $this->_params ) {
				$key = key($this->_params);
				$url .= '?' . $key . '=' . urlencode($this->_params[$key]);
				unset($this->_params[$key]);
				foreach( $this->_params as $key => $value ) {
					$url .= '&' . $key . '=' . urlencode($value);
				}
			}
			$this->_url = $url;
		}
		return $this->_url;
	}
	
	public function process() {
	
		$result = $this->execute();
	
		if( ($result === null) && ($this instanceof Action\AjaxAction) ) {
			$result = $this->view();
		}

		if( $result !== null ) {
			header( 'Content-type: application/json' );
			return json_encode( array(
				'status' => 'success',
				'time' => microtime(true),
				'content' => $result
			) );
		}
		return $this->view();
	}
	
	public function getDb() {
		return Database::getDb();
	}
	
	public function getQueryProvider() {
		return Db\QueryProvider::getProvider();
	}
	
	public function getParams() {
		return $this->_params;
	}
	
	public function getParam( $param ) {
		return $this->_params[ $param ];
	}
	
	public function getParamOrDefault( $param, $default ) {
		if( $this->hasParam( $param ) ) {
			return $this->getParam( $param );
		}
		return $default;
	}
	
	public function hasParam( $param ) {
		return isset( $this->_params[ $param ] );
	}
	
	public function action( $class, $params = array() ) {
	
		$class = 'Action\\' . $class;
		
		if( !class_exists( $class, true ) ) {
			header('HTTP/1.0 404 Not Found');
			throw new \Exception( "Page does not exists : " . $_GET['action'] );
		}
		
		$class = new $class( $params );
		
		$result = $class->execute();
		
		if( $result === null ) {
			return $class->view();
		}
		else {
			return $result;
		}
	}
	
	public function redirect( $path ) {
		header( 'Location: ' . $path );
		exit(0);
	}
}
